<?php

/**
 * MLEPP - ManiaLive Extending Plugin Pack
 *
 * -- MLEPP Plugin --
 * @name Statistics
 * @date 04-01-2011
 * @version r934
 * @website mlepp.trackmania.nl
 * @package MLEPP
 *
 * @author The MLEPP team
 * @copyright 2010 - 2011
 *
 * ---------------------------------------------------------------------
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
 * You are allowed to change things of use this in other projects, as
 * long as you leave the information at the top (name, date, version,
 * website, package, author, copyright) and publish the code under
 * the GNU General Public License version 3.
 * ---------------------------------------------------------------------
 */

namespace ManiaLivePlugins\MLEPP\Statistics;

use ManiaLive\Utilities\Console;
use ManiaLive\DedicatedApi\Connection;
use ManiaLive\Data\Storage;
use ManiaLive\Config\Loader;
use ManiaLive\PluginHandler\PluginHandler;

use ManiaLivePlugins\MLEPP\Core\Core;
use ManiaLivePlugins\MLEPP\Core\Mlepp;
use ManiaLivePlugins\MLEPP\Statistics\Rest;
use ManiaLive\Features\Admin\AdminGroup;

class Statistics extends \ManiaLive\PluginHandler\Plugin {

    private $mlepp;
    private $webServices;
    private $lastInfoSent;
    private $enabled = true;
    private $playerList = array();

    public static $username = '';
    public static $password = '';

	 /**
     * onInit()
     * Function called on initialisation of ManiaLive.
     *
     * @return void
     */

	function onInit() {
		// this needs to be set in the init section
		$this->setVersion(934);
        $this->setPublicMethod('getVersion');
        //ML Repository
        if(Core::RepositoryId != null){
            $this->setRepositoryId(Core::RepositoryId);
            $this->setRepositoryVersion(Core::RepositoryVersion);
        }
	}

    /**
     * onLoad()
     * Function called on loading of ManiaLive.
     *
     * @return void
     */

	function onLoad() {
		$this->enableDedicatedEvents();
        $this->enableStorageEvents();

		Console::println('['.date('H:i:s').'] [MLEPP] Plugin: Statistics r'.$this->getVersion() );
		$this->mlepp = Mlepp::getInstance();
    }

    function onReady() {
        if(self::$username == '') {
            self::$username = $this->storage->serverLogin;
        }

        $this->webServices = new \ManiaLivePlugins\MLEPP\Statistics\Rest(self::$username, self::$password);

        $this->giveInformation();
        $this->submitPlugins();

		foreach($this->storage->players as &$player) {
			$this->onPlayerDisconnect($player->login);
            $this->onPlayerConnect($player->login);
		}
		foreach($this->storage->spectators as &$spectator) {
			$this->onPlayerDisconnect($spectator->login, true);
            $this->onPlayerConnect($spectator->login, true);
		}
	}

    function onPlayerConnect($login, $isSpectator = false) {
        $player = $this->storage->getPlayerObject($login);
        $data = array();
        $data['login'] = $player->login;
        $data['nickname'] = $player->nickName;
        if(!$player->onlineRights) {
            $data['gametype'] = 'nations';
        } else {
            $data['gametype'] = 'united';
        }
        $data['clientversion'] = $player->clientVersion;
        $data['language'] = $player->language;
        $data['country'] = $player->path;
        if($isSpectator === true) {
            $data['spectator'] = '1';
        } else {
            $data['spectator'] = '0';
        }

        $this->playerList[$login] = $data;

        try {
            $response = $this->webServices->execute('POST', '/mlepp/player/join/', array($data));
        } catch(\Exception $e) {
            $this->handleExceptions($e);
        }
    }

    function onPlayerInfoChanged($playerinfo) {
        $spectatorStatus = $playerinfo['SpectatorStatus'];
        $data = array();
        $go = false;
        if($spectatorStatus == '0' && $this->playerList[$playerinfo['Login']]['spectator'] == '1') {
            // switched from spectator to player
            $data['login'] = $playerinfo['Login'];
            $data['spectator'] = '0';
            $this->playerList[$playerinfo['Login']]['spectator'] = '0';
            $go = true;
        } elseif($spectatorStatus != '0' && $this->playerList[$playerinfo['Login']]['spectator'] == '0') {
            // switched from player to spectator
            $data['login'] = $playerinfo['Login'];
            $data['spectator'] = '1';
            $this->playerList[$playerinfo['Login']]['spectator'] = '1';
            $go = true;
        }

        if($go === true) {
            try {
                $response = $this->webServices->execute('POST', '/mlepp/player/changespec/', array($data));
            } catch(\Exception $e) {
                $this->handleExceptions($e);
            }
        } else {
            print_r($playerinfo);
            print_r($this->playerList[$playerinfo['Login']]);
        }
    }

    function onPlayerDisconnect($login) {
        $player = $this->storage->getPlayerObject($login);
        $data = array();
        $data['login'] = $player->login;

        unset($this->playerList[$login]);

        try {
            $response = $this->webServices->execute('POST', '/mlepp/player/leave/', array($data));
        } catch(\Exception $e) {
            $this->handleExceptions($e);
        }
    }

    function giveInformation() {
        if($this->enabled) {
            $data = array();
            $data['serverLogin'] = $this->storage->serverLogin;
            $data['serverName'] = $this->storage->server->name;
            $version = $this->connection->getVersion();
            $data['serverVersion'] = array('Name' => $version->name, 'Version' => $version->version, 'Build' => $version->build);
            $data['manialiveVersion'] = \ManiaLiveApplication\Version;
            $data['mleppRelease'] = $this->callPublicMethod('MLEPP\Core', 'getVersion');
            $data['maxPlayers'] = $this->storage->server->currentMaxPlayers;
            $data['maxSpectators'] = $this->storage->server->currentMaxSpectators;
            $data['visibility'] = $this->storage->server->hideServer;
            $data['classHash'] = sha1_file(__FILE__);

            $freezone = 'no';

            $list = PluginHandler::getInstance()->getLoadedPluginsList();
            foreach($list as $pluginn) {
                $plugin = explode('\\', $pluginn);
                $author = array_shift($plugin);
                $package = implode('\\', $plugin);
                if($author == 'Freezone') {
                    $freezone = 'yes';
                }
            }

            $data['isFreezone'] = $freezone;

            try {
                $response = $this->webServices->execute('POST', '/mlepp/server/info/', array($data));
            } catch(\Exception $e) {
                $this->handleExceptions($e);
            }

            if($response) {
                Console::println($response->message);
            }

            $this->lastInfoSent = time("u");
        }
    }

    function submitPlugins() {
        if($this->enabled) {
            $list = PluginHandler::getInstance()->getLoadedPluginsList();
            $i = 0;
            $pluginlist = array();
            foreach($list as $pluginn) {
                $plugin = explode('\\', $pluginn);
                $author = array_shift($plugin);
                $package = implode('\\', $plugin);
                if($author == 'MLEPP') {
                    $version = $this->callPublicMethod('MLEPP\\'.$plugin[0], 'getVersion');
                    $pluginlist[] = array($package, $version);
                    $i++;
                }
            }

            $data['pluginList'] = $pluginlist;

            try {
                $response = $this->webServices->execute('POST', '/mlepp/server/plugins/', array($data));
            } catch(\Exception $e) {
                $this->handleExceptions($e);
            }

            if($response) {
                Console::println($response->message);
            }

            $this->lastInfoSent = time("u");
        }
    }

    function handleExceptions($e) {
        switch($e->getCode()) {
            case 401:
                $this->error_badPasswordMessage();
                $this->enabled = false;
                break;
            case 404:
                $this->error_servicesOffline();
                $this->enabled = false;
                break;
            case 601:
                $this->error_deprecatedFunction();
                break;
            case 600:
                $this->error_servicesOffline();
                $this->enabled = false;
                break;
        }
        throw $e;
    }

    function error_badPasswordMessage() {
        Console::println('['.date('H:i:s').'] [MLEPP] [Statistics] [401] Bad API Password, please check your configuration file! Statistics disabled.');
    }

    function error_servicesOffline() {
        Console::println('['.date('H:i:s').'] [MLEPP] [Statistics] [404/600] Services offline! Statistics disabled.');
    }

    function error_deprecatedFunction() {
        Console::println('['.date('H:i:s').'] [MLEPP] [Statistics] [601] You are using an obsolete version of Statistics!');
    }
}
?>